<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/icon.png">
  <link rel="mask-icon" href="/blog/images/icon.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bgape002.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="什么是日志日志是一种可以追踪某些软件运行时所发生事件的方法。软件开发人员可以向他们的代码中调用日志记录相关的方法来表明发生了某些事情。一个事件可以用一个可包含可选变量数据的消息来描述。此外，事件也有重要性的概念，这个重要性也可以被称为严重性级别（level）。 日志的等级   级别 何时使用    DEBUG 详细信息，典型地调试问题时会感兴趣。 详细的debug信息。   INFO 证明事情按预">
<meta property="og:type" content="article">
<meta property="og:title" content="logging模块">
<meta property="og:url" content="https://bgape002.gitee.io/2022/07/26/logging%E6%A8%A1%E5%9D%97/index.html">
<meta property="og:site_name" content="bgape002">
<meta property="og:description" content="什么是日志日志是一种可以追踪某些软件运行时所发生事件的方法。软件开发人员可以向他们的代码中调用日志记录相关的方法来表明发生了某些事情。一个事件可以用一个可包含可选变量数据的消息来描述。此外，事件也有重要性的概念，这个重要性也可以被称为严重性级别（level）。 日志的等级   级别 何时使用    DEBUG 详细信息，典型地调试问题时会感兴趣。 详细的debug信息。   INFO 证明事情按预">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bgape002.gitee.io/blog/images/loggingFlow.png">
<meta property="article:published_time" content="2022-07-26T01:35:46.000Z">
<meta property="article:modified_time" content="2022-08-08T06:48:16.404Z">
<meta property="article:author" content="bgape002">
<meta property="article:tag" content="logging">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://bgape002.gitee.io/blog/images/loggingFlow.png">

<link rel="canonical" href="https://bgape002.gitee.io/2022/07/26/logging%E6%A8%A1%E5%9D%97/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>logging模块 | bgape002</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">bgape002</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">淡泊明志，宁静致远</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">66</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">27</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">61</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bgape002.gitee.io/2022/07/26/logging%E6%A8%A1%E5%9D%97/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/head.png">
      <meta itemprop="name" content="bgape002">
      <meta itemprop="description" content="mail: bgape002@163.com">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="bgape002">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          logging模块
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2022-07-26 09:35:46" itemprop="dateCreated datePublished" datetime="2022-07-26T09:35:46+08:00">2022-07-26</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2022-08-08 14:48:16" itemprop="dateModified" datetime="2022-08-08T14:48:16+08:00">2022-08-08</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/blog/2022/07/26/logging%E6%A8%A1%E5%9D%97/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/blog/2022/07/26/logging%E6%A8%A1%E5%9D%97/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="什么是日志"><a href="#什么是日志" class="headerlink" title="什么是日志"></a>什么是日志</h3><p>日志是一种可以追踪某些软件运行时所发生事件的方法。软件开发人员可以向他们的代码中调用日志记录相关的方法来表明发生了某些事情。一个事件可以用一个可包含可选变量数据的消息来描述。此外，事件也有重要性的概念，这个重要性也可以被称为严重性级别（level）。</p>
<h3 id="日志的等级"><a href="#日志的等级" class="headerlink" title="日志的等级"></a>日志的等级</h3><table>
<thead>
<tr>
<th align="left">级别</th>
<th align="left">何时使用</th>
</tr>
</thead>
<tbody><tr>
<td align="left">DEBUG</td>
<td align="left">详细信息，典型地调试问题时会感兴趣。 详细的debug信息。</td>
</tr>
<tr>
<td align="left">INFO</td>
<td align="left">证明事情按预期工作。 关键事件。</td>
</tr>
<tr>
<td align="left">WARNING</td>
<td align="left">表明发生了一些意外，或者不久的将来会发生问题（如‘磁盘满了’）。软件还是在正常工作。</td>
</tr>
<tr>
<td align="left">ERROR</td>
<td align="left">由于更严重的问题，软件已不能执行一些功能了。 一般错误消息。</td>
</tr>
<tr>
<td align="left">CRITICAL</td>
<td align="left">严重错误，表明软件已不能继续运行了。</td>
</tr>
<tr>
<td align="left">NOTICE</td>
<td align="left">不是错误，但是可能需要处理。普通但是重要的事件。</td>
</tr>
<tr>
<td align="left">ALERT</td>
<td align="left">需要立即修复，例如系统数据库损坏。</td>
</tr>
<tr>
<td align="left">EMERGENCY</td>
<td align="left">紧急情况，系统不可用（例如系统崩溃），一般会通知所有用户。</td>
</tr>
</tbody></table>
<h3 id=""><a href="#" class="headerlink" title=""></a><span id="more"></span></h3><h3 id="logging的日志等级"><a href="#logging的日志等级" class="headerlink" title="logging的日志等级"></a>logging的日志等级</h3><table>
<thead>
<tr>
<th align="left">日志等级（level）</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">DEBUG</td>
<td align="left">最详细的日志信息，典型应用场景是 问题诊断</td>
</tr>
<tr>
<td align="left">INFO</td>
<td align="left">信息详细程度仅次于DEBUG，通常只记录关键节点信息，用于确认一切都是按照我们预期的那样进行工作</td>
</tr>
<tr>
<td align="left">WARNING</td>
<td align="left">当某些不期望的事情发生时记录的信息（如，磁盘可用空间较低），但是此时应用程序还是正常运行的</td>
</tr>
<tr>
<td align="left">ERROR</td>
<td align="left">由于一个更严重的问题导致某些功能不能正常运行时记录的信息</td>
</tr>
<tr>
<td align="left">CRITICAL</td>
<td align="left">当发生严重错误，导致应用程序不能继续运行时记录的信息</td>
</tr>
</tbody></table>
<p><strong>列表中的日志等级是从上到下依次增高，日志内容依次减少，即DEBUG可以显示所有日志，CRITICAL只能显示自己。</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> logging</span><br><span class="line"></span><br><span class="line">logging.debug(<span class="string">&quot;debug_msg&quot;</span>)</span><br><span class="line">logging.info(<span class="string">&quot;info_msg&quot;</span>)</span><br><span class="line">logging.warning(<span class="string">&quot;warning_msg&quot;</span>)</span><br><span class="line">logging.error(<span class="string">&quot;error_msg&quot;</span>)</span><br><span class="line">logging.critical(<span class="string">&quot;critical_msg&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;output</span></span><br><span class="line"><span class="string">WARNING:root:warning_msg</span></span><br><span class="line"><span class="string">ERROR:root:error_msg</span></span><br><span class="line"><span class="string">CRITICAL:root:critical_msg</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h3 id="logging输出日志流程"><a href="#logging输出日志流程" class="headerlink" title="logging输出日志流程"></a>logging输出日志流程</h3><p><img src="/blog/images/loggingFlow.png" alt="."></p>
<h3 id="Handler类"><a href="#Handler类" class="headerlink" title="Handler类"></a>Handler类</h3><figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="bullet">-</span> BaseRotatingHandler</span><br><span class="line"><span class="bullet">-</span> Rotating Filehandler    # 滚动的多日志输出，按照时间or其他方式去生成多个日志</span><br><span class="line"><span class="bullet">-</span> TimedRotatingfilehandler</span><br><span class="line"></span><br><span class="line"><span class="bullet">-</span> Sockethandler</span><br><span class="line"><span class="bullet">-</span> Dataaramhandler</span><br><span class="line"><span class="bullet">-</span> Smtphandler</span><br><span class="line"><span class="bullet">-</span> Sysloghandler</span><br><span class="line"><span class="bullet">-</span> Nteventloghandler</span><br><span class="line"><span class="bullet">-</span> Httphandler</span><br><span class="line"><span class="bullet">-</span> WatchedFilehandler</span><br><span class="line"><span class="bullet">-</span> Qutelehandler</span><br><span class="line"><span class="bullet">-</span> Nullhandler</span><br></pre></td></tr></table></figure>

<h3 id="Formatters格式"><a href="#Formatters格式" class="headerlink" title="Formatters格式"></a>Formatters格式</h3><table>
<thead>
<tr>
<th align="left">属性</th>
<th align="left">格式</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">asctime</td>
<td align="left">%(asctime)s</td>
<td align="left">日志产生的时间，默认格式为msecs2003-07-0816:49:45,896</td>
</tr>
<tr>
<td align="left">msecs</td>
<td align="left">%(msecs)d</td>
<td align="left">日志生成时间的亳秒部分</td>
</tr>
<tr>
<td align="left">created</td>
<td align="left">%(created)f</td>
<td align="left">time.tme)生成的日志创建时间戳</td>
</tr>
<tr>
<td align="left">message</td>
<td align="left">%(message)s</td>
<td align="left">具体的日志信息</td>
</tr>
<tr>
<td align="left">filename</td>
<td align="left">%(filename)s</td>
<td align="left">生成日志的程序名</td>
</tr>
<tr>
<td align="left">name</td>
<td align="left">%(name)s</td>
<td align="left">日志调用者</td>
</tr>
<tr>
<td align="left">funcname</td>
<td align="left">%( funcname)s</td>
<td align="left">调用日志的函数名</td>
</tr>
<tr>
<td align="left">levelname</td>
<td align="left">%(levelname)s</td>
<td align="left">日志级別( DEBUG,INFO, WARNING, ‘ERRORCRITICAL)</td>
</tr>
<tr>
<td align="left">levene</td>
<td align="left">%( leveling)s</td>
<td align="left">日志级别对应的数值</td>
</tr>
<tr>
<td align="left">lineno</td>
<td align="left">%(lineno)d</td>
<td align="left">日志所针对的代码行号（如果可用的话）</td>
</tr>
<tr>
<td align="left">module</td>
<td align="left">%( module)s</td>
<td align="left">生成日志的模块名</td>
</tr>
<tr>
<td align="left">pathname</td>
<td align="left">%( pathname)s</td>
<td align="left">生成日志的文件的完整路径</td>
</tr>
<tr>
<td align="left">process</td>
<td align="left">%( (process)d</td>
<td align="left">生成日志的进程D（如果可用）</td>
</tr>
<tr>
<td align="left">processname</td>
<td align="left">(processname)s</td>
<td align="left">进程名（如果可用）</td>
</tr>
<tr>
<td align="left">thread</td>
<td align="left">%(thread)d</td>
<td align="left">生成日志的线程D（如果可用）</td>
</tr>
<tr>
<td align="left">threadname</td>
<td align="left">%( threadname)s</td>
<td align="left">线程名（如果可用)</td>
</tr>
</tbody></table>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;logging packages</span></span><br><span class="line"><span class="string">Loggers: 记录器，提供应用程序代码能直接使用的接口；</span></span><br><span class="line"><span class="string">Handlers: 处理器，将记录器产生的日志发送至目的地；</span></span><br><span class="line"><span class="string">Fiters: 过滤器，提供更好的粒度控制，决定哪些日志会被输出；</span></span><br><span class="line"><span class="string">Formatters: 格式化器，设置日志的组成结构和消息字段</span></span><br><span class="line"><span class="string">*****************************</span></span><br><span class="line"><span class="string">flow charts</span></span><br><span class="line"><span class="string">1. 创建一个logger并设置默认等级</span></span><br><span class="line"><span class="string">2. 创建屏幕StreamHandle // 创建文件 FileHandle</span></span><br><span class="line"><span class="string">3. 设置日志等级</span></span><br><span class="line"><span class="string">4. 创建formatter // 格式化样式 %( )s</span></span><br><span class="line"><span class="string">5. 用formatter渲染所有的Handle</span></span><br><span class="line"><span class="string">6. 将所有Handle加入logger内</span></span><br><span class="line"><span class="string">7.程序调用logger</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">import</span> logging</span><br><span class="line"><span class="comment"># 记录器</span></span><br><span class="line">loggerName = <span class="string">&#x27;bgape002.top.pack&#x27;</span></span><br><span class="line">logger = logging.getLogger(loggerName)</span><br><span class="line">logger.setLevel(logging.DEBUG)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 处理器</span></span><br><span class="line">consoleHandler = logging.StreamHandler()</span><br><span class="line">consoleHandler.setLevel(logging.DEBUG)  <span class="comment"># 未设置，默认使用logger级别</span></span><br><span class="line">fileHandler = logging.FileHandler(filename=<span class="string">&#x27;demo02.log&#x27;</span>, mode=<span class="string">&#x27;w&#x27;</span>)</span><br><span class="line">fileHandler.setLevel(logging.WARNING)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 过滤器</span></span><br><span class="line">flt = logging.Filter(<span class="string">&#x27;bgape002.top&#x27;</span>)  <span class="comment"># 如果loggerName不包含bgape002.top前缀，则过滤</span></span><br><span class="line">logger.addFilter(flt)  <span class="comment"># 添加过滤器</span></span><br><span class="line"><span class="comment"># fltconsl = logging.Filter(&#x27;top&#x27;)</span></span><br><span class="line"><span class="comment"># fileHandler.addFilter(fltconsl)  # 给fileHandle添加过滤器</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 格式化器</span></span><br><span class="line">formatter = logging.Formatter(<span class="string">&#x27;%(asctime)s|%(levelname)8s|%(filename)s[:%(lineno)d]|%(message)s&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置处理器格式</span></span><br><span class="line">consoleHandler.setFormatter(formatter)</span><br><span class="line">fileHandler.setFormatter(formatter)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 记录器添加处理器</span></span><br><span class="line">logger.addHandler(consoleHandler)</span><br><span class="line">logger.addHandler(fileHandler)</span><br><span class="line"></span><br><span class="line">name = <span class="string">&#x27;bgape&#x27;</span>; age = <span class="number">28</span></span><br><span class="line">logger.debug(<span class="string">&#x27;name %s, age %d, debug&#x27;</span>, name, age)</span><br><span class="line">logger.info(<span class="string">&#x27;name %s, age %d, info&#x27;</span>, name, age)</span><br><span class="line">logger.warning(<span class="string">&#x27;name %s, age %d, warning&#x27;</span> % (name, age))</span><br><span class="line">logger.error(<span class="string">&#x27;name &#123;&#125;, age &#123;&#125;, error&#x27;</span>.<span class="built_in">format</span>(name, age))</span><br><span class="line">logger.critical(<span class="string">f&#x27;name <span class="subst">&#123;name&#125;</span>, age <span class="subst">&#123;age&#125;</span>, critical&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;output</span></span><br><span class="line"><span class="string">2022-07-26 09:59:44,615|   DEBUG|demo02.py[:48]|name bgape, age 28, debug</span></span><br><span class="line"><span class="string">2022-07-26 09:59:44,615|    INFO|demo02.py[:49]|name bgape, age 28, info</span></span><br><span class="line"><span class="string">2022-07-26 09:59:44,615| WARNING|demo02.py[:50]|name bgape, age 28, warning</span></span><br><span class="line"><span class="string">2022-07-26 09:59:44,616|   ERROR|demo02.py[:51]|name bgape, age 28, error</span></span><br><span class="line"><span class="string">2022-07-26 09:59:44,616|CRITICAL|demo02.py[:52]|name bgape, age 28, critical</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="logging-config载入配置文件"><a href="#logging-config载入配置文件" class="headerlink" title="logging.config载入配置文件"></a><code>logging.config</code>载入配置文件</h3><p>配置文件类型可支持两种类型</p>
<ul>
<li><p>可以由<code>configparse</code>模块解析的配置文件格式</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># logging.conf</span></span><br><span class="line"></span><br><span class="line">[<span class="string">loggers</span>]</span><br><span class="line"><span class="string">keys=root,bgape</span></span><br><span class="line"></span><br><span class="line">[<span class="string">handlers</span>]</span><br><span class="line"><span class="string">keys=fileHandler,consoleHandler</span></span><br><span class="line"></span><br><span class="line">[<span class="string">formatters</span>]</span><br><span class="line"><span class="string">keys=simpleFormatter</span></span><br><span class="line"></span><br><span class="line">[<span class="string">logger_root</span>]</span><br><span class="line"><span class="string">level=DEBUG</span></span><br><span class="line"><span class="string">handlers=consoleHandler</span></span><br><span class="line"></span><br><span class="line">[<span class="string">logger_bgape</span>]</span><br><span class="line"><span class="string">level=DEBUG</span></span><br><span class="line"><span class="string">handlers=fileHandler,consoleHandler</span></span><br><span class="line"><span class="string">qualname=bgape</span></span><br><span class="line"><span class="string">propagate=0</span></span><br><span class="line"></span><br><span class="line">[<span class="string">handler_consoleHandler</span>]</span><br><span class="line"><span class="string">class=StreamHandler</span></span><br><span class="line"><span class="string">args=(sys.stdout,)</span></span><br><span class="line"><span class="string">level=DEBUG</span></span><br><span class="line"><span class="string">formatter=simpleFormatter</span></span><br><span class="line"></span><br><span class="line">[<span class="string">handler_fileHandler</span>]</span><br><span class="line"><span class="string">class=handlers.TimedRotatingFileHandler</span></span><br><span class="line"><span class="string">args=(&#x27;demo03.log&#x27;,&#x27;midnight&#x27;,1,0)</span></span><br><span class="line"><span class="string">level=DEBUG</span></span><br><span class="line"><span class="string">formatter=simpleFormatter</span></span><br><span class="line"></span><br><span class="line">[<span class="string">formatter_simpleFormatter</span>]</span><br><span class="line"><span class="string">format=%(asctime)s|%(levelname)8s|%(filename)s[:%(lineno)d]|%(message)s</span></span><br><span class="line"><span class="string">datefmt=%Y-%m-%d</span> <span class="string">%H:%M:%S</span></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
<li><p>字典格式，一般以json格式保存在本地</p>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 配置文件方式处理日志</span></span><br><span class="line"><span class="keyword">import</span> logging</span><br><span class="line"><span class="keyword">import</span> logging.config</span><br><span class="line"></span><br><span class="line">logging.config.fileConfig(<span class="string">&#x27;logging.conf&#x27;</span>)</span><br><span class="line"></span><br><span class="line">rootLogger = logging.getLogger()</span><br><span class="line">bgapeLogger = logging.getLogger(<span class="string">&#x27;bgape&#x27;</span>)</span><br><span class="line"></span><br><span class="line">rootLogger.debug(<span class="string">&quot;Debug&quot;</span>)</span><br><span class="line">bgapeLogger.debug(<span class="string">&#x27;Debug.bgape&#x27;</span>)</span><br><span class="line"></span><br><span class="line">a = <span class="string">&#x27;bgape&#x27;</span></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    <span class="built_in">int</span>(a)</span><br><span class="line"><span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">    <span class="comment"># bgapeLogger.error(e)</span></span><br><span class="line">    bgapeLogger.exception(e)</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line"><span class="string">&quot;&quot;&quot;output</span></span><br><span class="line"><span class="string">2022-07-26 10:06:21|   DEBUG|demo03.py[:11]|Debug</span></span><br><span class="line"><span class="string">2022-07-26 10:06:21|   DEBUG|demo03.py[:12]|Debug.bgape</span></span><br><span class="line"><span class="string">2022-07-26 10:06:21|   ERROR|demo03.py[:19]|invalid literal for int() with base 10: &#x27;bgape&#x27;</span></span><br><span class="line"><span class="string">Traceback (most recent call last):</span></span><br><span class="line"><span class="string">  File &quot;D:\documents\lang\python\pyBasement\loggingL\demo03.py&quot;, line 16, in &lt;module&gt;</span></span><br><span class="line"><span class="string">    int(a)</span></span><br><span class="line"><span class="string">ValueError: invalid literal for int() with base 10: &#x27;bgape&#x27;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>



<h3 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h3><font size=2>

<p>[1] <a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1sK4y1x7e1?spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=5f03bdbb9a8460c7ae08f9cdea23577b">Python基础之标准库logging 你还在用print来调试程序吗，OUT啦</a></p>
<p>[2] <a target="_blank" rel="noopener" href="https://www.cnblogs.com/kangshuaibo/p/14700833.html">标准库系列：logging 日志打印 </a></p>
</font>


    </div>

    
    
    

      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/blog/tags/logging/" rel="tag"><i class="fa fa-tag"></i> logging</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2022/07/25/edif-version200/" rel="prev" title="edif_version200">
      <i class="fa fa-chevron-left"></i> edif_version200
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2022/07/26/print%E8%BE%93%E5%87%BA%E9%A2%9C%E8%89%B2%E5%AD%97/" rel="next" title="print输出颜色字">
      print输出颜色字 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>


        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E6%97%A5%E5%BF%97"><span class="nav-number">1.</span> <span class="nav-text">什么是日志</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%97%A5%E5%BF%97%E7%9A%84%E7%AD%89%E7%BA%A7"><span class="nav-number">2.</span> <span class="nav-text">日志的等级</span></a></li><li class="nav-item nav-level-3"><a class="nav-link"><span class="nav-number">3.</span> <span class="nav-text"></span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#logging%E7%9A%84%E6%97%A5%E5%BF%97%E7%AD%89%E7%BA%A7"><span class="nav-number">4.</span> <span class="nav-text">logging的日志等级</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#logging%E8%BE%93%E5%87%BA%E6%97%A5%E5%BF%97%E6%B5%81%E7%A8%8B"><span class="nav-number">5.</span> <span class="nav-text">logging输出日志流程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Handler%E7%B1%BB"><span class="nav-number">6.</span> <span class="nav-text">Handler类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Formatters%E6%A0%BC%E5%BC%8F"><span class="nav-number">7.</span> <span class="nav-text">Formatters格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#logging-config%E8%BD%BD%E5%85%A5%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="nav-number">8.</span> <span class="nav-text">logging.config载入配置文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E9%93%BE%E6%8E%A5"><span class="nav-number">9.</span> <span class="nav-text">参考链接</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="bgape002"
      src="/blog/images/head.png">
  <p class="site-author-name" itemprop="name">bgape002</p>
  <div class="site-description" itemprop="description">mail: bgape002@163.com</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">61</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">66</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2021 – 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">bgape002</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'szhBf0Qamzsowubi1WnkXmUj-gzGzoHsz',
      appKey     : 'WpwxoK0fVJHvhzWwakr9vbpA',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
